<?php

// +----------------------------------------------------------------------
// | TOPThink [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2011 http://topthink.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------
// $Id$
include "Page.class.php";

class IndexAction extends Action {

    public function index() {
        $map['status'] = 0;
        $pdffiles = M("archive")->where($map)->select();
        $this->assign('pdffiles', $pdffiles);
        $jxjy = $this->getNews('6');
        $zlzn = $this->getNews('7');
        $zxzy = $this->getNews('8');
        $xlcl = $this->getInfo('psy');
        $this->assign('jxjy', $jxjy);
        $this->assign('zlzn', $zlzn);
        $this->assign('xlcl', $xlcl);
        $this->assign('zxzy', $zxzy);
        $this->assign('pdffiles', $pdffiles);
        $this->set_seo_meta('首页', '温州一医');
        $this->display();
    }

    public function read() {
        $id = intval($_GET['id']);
        $module = M("Form");
        $news = $module->where("id=$id")->select();
        $latest = $module->limit(10)->order('id desc')->select();
        $this->assign('news', $news);
        $this->assign('latest', $latest);
        $this->set_seo_meta($news[0]['title'] . '_详细内容');
        $this->display();
    }

    public function category() {
        $id = intval($_GET['id']);
        $module = M("Form");
        $map['category'] = $id;
        $news = $module->where($map)->select();
        $category = $module->where("category=$id")->limit(10)->order('id desc')->select();
        $latest = $module->limit(10)->order('id desc')->select();
        $this->assign('news', $news);
        $this->assign('category', $category);
        $this->assign('latest', $latest);
        $this->set_seo_meta('文章资讯_分类浏览');
        $this->display();
    }

    private function getNews($category, $num = 10) {
        $return = array();
        $module = M("Form");
        $map['status'] = 1;
        $map['category'] = $category;
        $return = $module->where($map)->limit($num)->select();
        return $return;
    }

    private function getInfo($table, $num = 10) {
        $return = array();
        $module = M("$table");
        $map['status'] = 1;
        $return = $module->where($map)->limit($num)->select();
        return $return;
    }

    public function tests() {
        $module = M('psy');
        $map['status'] = 1;
        $psydata = $module->where($map)->select();
        $latest = $module->where($map)->limit(10)->order('id desc')->select();
        $this->assign('latest', $latest);
        $this->assign('psy', $psydata);
        $this->set_seo_meta('心理测量');
        $this->display();
    }

    public function dotest() {
        $id = intval($_GET['id']);
        $psydata = M('psy')->getById($id);
        $psysubjects = explode(',', $psydata['subjects']);
        $map['id'] = array('in', $psysubjects);
        $psybase = M('psybase')->where($map)->select();
        $count = count($psybase);
        for ($i = 0; $i < $count; $i++) {
            $psy[$i]['id'] = $psybase[$i]['id'];
            $psy[$i]['title'] = $psybase[$i]['title'];
            $psy[$i]['type'] = $psybase[$i]['type'];
            $score = explode('|||', $psybase[$i]['score']);
            unset($score[4]);
            $psy[$i]['score'] = $score;
            $option = explode('|||', $psybase[$i]['option']);
            unset($option[4]);
            $psy[$i]['option'] = $option;
        }
        $this->assign('title', $psydata['title']);
        $this->assign('remark', $psydata['remark']);
        $this->assign('id', $id);
        $this->assign('psysubject', $psy);
        $this->display();
    }

    public function doexam() {
        $which = array_pop($_POST);
        switch ($which) {
            case 1:
                $subject = 'sds';
                break;
            case 2:
                $subject = 'sas';
                break;
            case 3:
                $subject = 'had';
                break;
            case 5:
                $subject = 'mmse';
                break;
            case 6:
                $subject = 'astyle';
                break;
            case 7:
                $subject = 'bdi';
                break;
            case 8:
                $subject = 'adl';
                break;
            case 9:
                $subject = 'pizz';
                break;
            case 10:
                $subject = 'gds';
                break;
        }
       
        $func = 'the_' . $subject . '_answer';
        $result = $this->$func($_POST);
        $latest = D('Form')->limit(10)->order('id desc')->select();
        $this->assign('latest', $latest);
        $this->assign('score', $result['score']);
        $this->assign('result', $result['result']);
        $this->assign('unusually', $result['unusually']);
        $this->display();
    }

    /**
     * 日常生活能力量表（ADL）
     * 评分标准:
     * 评定结果可按总分、分量表分和单项分进行分析
     * 总分量小于等于16分，为完全正常，大于16分有不同程度的功能下降，最高64分。
     * 单项分1分为正常，2～4分为功能下降。凡有2项或2项以上≥3分，或总分≥22，为功能有明显障碍*
     * @param <type> $post
     * @return <type>
     */
    private function the_adl_answer($post) {
        $module = M('Psybase');
        $return = array();
        $score = array_sum($post);
        foreach ($post as $k => $v) {
            if ($v >= 3) {
                $unusually_id[] = str_replace('options', '', $k);
            }
        }
        $unusually_map['id'] = array('in', $unusually_id);
        $unusually_data = $module->where($unusually_map)->select();
        $optcount = array_count_values($post);
        if ($score <= 16 && $optcount['3'] < 2 && $optcount['4'] < 2 && ($optcount['3'] + $optcount['4']) < 2) {
            $result = '日常生活能力完全正常';
        }
        if($score > 16 && $score < 22){
            $result = '部分日常生活能力有不同程度的功能下降';
        }
        if ($score >= 22 || $optcount['3'] >= 2 || $optcount['4'] >= 2 || ($optcount['3'] + $optcount['4']) >= 2) {
            $result = '日常生活能力有明显障碍';
        }
        $return['score'] = $score;
        $return['result'] = $result;
        $return['unusually'] = $unusually_data;
        return $return;
    }

    /**
     * 老年抑郁量表(GDS-30)
     * 评分标准:
     * 0—10分可视为正常范围，即无抑郁症，
     * 11—20分显示轻度抑郁，
     * 21—30分为中重度抑郁
     * @param <type> $post
     * @return <type>
     */
    private function the_gds_answer($post){
        $return = array();
        $score = array_sum($post);
        $return['score'] = $score;
        if($score <= 10){
            $result = '无抑郁症';
        }
        if($score > 10 && $score <=20){
            $result = '轻度抑郁';
        }
        if($score > 20){
            $result = '重度抑郁';
        }
        $return['result'] = $result;
        return $return;
    }

    /**
     * BECK抑郁自评问卷（BDI）
     * 评分标准:
     * 0-5 无抑郁
     * 5-7 轻度抑郁
     * 8-15 中度抑郁
     * 16 以上重度抑郁
     * @param <type> $post
     * @return array
     */
    private function the_bdi_answer($post){
        $return = array();
        $score = array_sum($post);
        $return['score'] = $score;
        if($score <= 5){
            $result = '无抑郁';
        }
        if($score > 5 && $score <= 7){
            $result = '轻度抑郁';
        }
        if($score > 7 && $score <= 15){
            $result = '中度抑郁';
        }
        if($score > 15){
            $result = '重度抑郁';
        }
        $return['result'] = $result;
        return $return;
    }

    /**
     * 自评抑郁量表 （SDS）
     * 评分标准:
     * 原始分、标准分：将每项得分相加，即得到原始分（亦称粗分），粗分乘以1.25以后取其整数部份，就得到标准总分
     * 抑郁严重度＝各条目累计分÷80 (最高总分)。指数范围为0.25～1.0，指数越高，抑郁程度越重。
     * 指数在0.5以下者为无抑郁;0.50～0.59为轻微至轻度抑郁;0.60～0.69为中至重度抑郁;0.70以上为重度抑郁
     * @param <type> $post
     * @return array
     */
    private function the_sds_answer($post){
        $return = array();
        $score = array_sum($post);
        $return['score'] = $score;
        $persent = $score / 80;
        if($persent <= 0.5){
            $result = '无抑郁';
        }
        if($persent > 0.5 && $persent <= 0.59){
            $result = '轻微至轻度抑郁';
        }
        if($persent > 0.59 && $persent <= 0.69){
            $result = '中至重度抑郁';
        }
        if($persent > 0.7){
            $result = '重度抑郁';
        }
        $return['result'] = $result;
        return $return;
    }

    /**
     * 焦虑自评量表 (SAS)
     * 评分标准：
     * 40≤总分＜48为轻度焦虑；48≤总分＜56为中度焦虑；56≤总分为中度焦虑
     * @param <type> $post
     * @return array
     */
    private function the_sas_answer($post){
        $return = array();
        $score = array_sum($post);
        $return['score'] = $score;
       if($score >= 40 && $score < 48){
            $result = '轻度焦虑';
        }
        if($score >= 48 && $score < 56){
            $result = '中度焦虑';
        }
        if($score >= 56){
            $result = '中度焦虑';
        }
        $return['result'] = $result;
        return $return;
    }
    
    private function the_had_answer($post){
        $return = array();
        echo $score = array_sum($post);
        $return['score'] = $score;
        if($score){

        }
    }

    public function insert() {
        $User = D('Member');
        if ($_SESSION['verify'] != md5($_POST['yzm'])) {
            $this->error('验证码错误！');
        } else {
            if ($User->create()) {
                $result = $User->add($data);
                if ($result) {
                    $this->success('成功');
                } else {
                    $this->error('失败');
                }
            } else {
                $this->error($User->getError());
            }
            $this->display();
        }
    }

    public function message() {
        $module = D('Message');
        $data = $module->where('status=1')->limit(10)->order('id DESC')->select();
        $category = D('Form')->limit(10)->order('id desc')->select();
        $this->assign('data', $data);
        $this->assign('category', $category);
        $this->set_seo_meta('在线留言');
        $this->display();
    }

    public function domessage() {
        $module = D('Message');
        $data = array();
//        $data['email'] = addslashes(trim($_POST['TxtEmail']));
        $data['title'] = addslashes(trim($_POST['TxtTitle']));
        $data['telephone'] = addslashes(trim($_POST['TxtPhone']));
        $data['content'] = addslashes(trim($_POST['TxtContent']));
        $data['status'] = 0;
        $data['createat'] = time();
        $act = $module->add($data);
        if ($act) {
            $this->success('留言添加成功,我们会在第一时间给你回复.');
        } else {
            $this->error('数据库繁忙,请稍后再试!');
        }
    }

    public function archive() {
		$documentdir = 'C:\pdf';
        $module = M('archive');
        $map['status'] = 0;
        $pdffiles = $module->where($map)->select();
        $this->assign('pdffiles', $pdffiles);
        $latest = D('Form')->limit(10)->order('id desc')->select();
        $this->assign('latest', $latest);
        $this->assign('pdffiles', $pdffiles);
        $this->set_seo_meta('文档下载	');
		$this->assign('docdir',$documentdir);
        $this->display();
    }
	
	public function download() {
		$file_name = trim($_GET['FileName']);
		$file_dir = "C:\pdf";
		if(!file_exists($file_dir."\\".$file_name)){
			echo   "文件找不到"; 
		  	exit;   
		}else{ 
			$file = fopen($file_dir . $file_name, "r");
			Header("Content-type: application/octet-stream");
			Header("Accept-Ranges: bytes");
			Header("Accept-Length: ".filesize($file_dir . $file_name));
			Header("Content-Disposition: attachment; filename=" . $file_name);
			echo fread($file,filesize($file_dir . $file_name));
			fclose($file);
			exit();
		}
	}

    private function searchDir($path, &$data) {
        if (is_dir($path)) {
            $dp = dir($path);
            while ($file = $dp->read()) {
                if ($file != '.' && $file != '..') {
                    $this->searchDir($path . '/' . $file, $data);
                }
            }
            $dp->close();
        }
        if (is_file($path)) {
            $data[] = substr($path, strripos($path, '/') + 1);
        }
    }

    public function draw() {
        $file = $_GET['doc'] . ".pdf";
        $exists = file_exists('myfile.doc');
        $this->assign('file', $file);
        $latest = D('Form')->limit(10)->order('id desc')->select();
        $this->assign('latest', $latest);
        $this->set_seo_meta('在线浏览文档');
        $this->display();
    }

    public function papers() {
//        $dir = "C:\pdf";
//        $data = array();
//        $this->searchDir($dir, $data);
//        $pdffiles = $data;
        $module = M('archive');
        $map['status'] = 0;
        $map['category'] = 1;
        $pdffiles = $module->where($map)->select();
        $this->assign('pdffiles', $pdffiles);
        $module = M("Testbase");
        $latest = D('Form')->limit(10)->order('id desc')->select();
        $this->assign('latest', $latest);
        $this->set_seo_meta('学习档案_继续教育');
        $this->display();
    }

    public function testtips() {
		$user_id = intval($_SESSION['user_id']);
        $id = intval($_GET['id']);
        $this->assign('id', $id);
        $module = M("Testbase");
        $latest = M("Form")->limit(10)->order('id desc')->select();
        $this->assign('latest', $latest);
        $this->set_seo_meta('参加测试注意事项');
		$this->assign('user_id',$user_id);
        $this->display();
    }

    public function dopaper() {
        //测试前的登录检测
        $this->issignin();
        //传过来id
        $id = intval($_GET['id']);
        $psydata = M('testbase')->getById($id);
        $psysubjects = explode(',', $psydata['subjects']);
        $map['id'] = array('in', $psysubjects);
        $psybase = M('testsubject')->where($map)->select();
        $count = count($psybase);
        $radio_count = 0;
		$check_count = 0;
		$bool_count = 0;
        for ($i = 0; $i < $count; $i++) {
            $psy[$i]['id'] = $psybase[$i]['id'];
            $psy[$i]['title'] = $psybase[$i]['title'];
            $psy[$i]['type'] = $psybase[$i]['type'];
			if($psy[$i]['type'] == 1){
				$radio_count = $radio_count + 1;
			}
			if($psy[$i]['type'] == 3){
				$bool_count = $bool_count + 1;
			}
            $score = explode('|||', $psybase[$i]['score']);
            unset($score[4]);
            $psy[$i]['score'] = $score;
            $option = explode('|||', $psybase[$i]['option']);
            unset($option[4]);
            $psy[$i]['option'] = $option;
        }
        $this->assign('title', $psydata['title']);
        $this->assign('remark', $psydata['remark']);
        $this->assign('id', $id);
        $this->assign('psysubject', $psy);
		$this->assign('radio_count',$radio_count+$bool_count);
        $this->display();
    }

    public function paperanswer() {
        $this->issignin();
        $bId = intval($_POST['id']);
        $sId = M('Testbase')->where("id=$bId")->select();
        $subjects = explode(',', $sId[0]['subjects']);
        $answers = array();
        foreach ($subjects as $k => $v) {
            $answer = "answer" . $v;
            $answers[$k]['answer'] = $_POST["$answer"];
            $answers[$k]['sid'] = $v;
        }
        foreach ($answers as $kk => $vv) {
            $thisoption[] = $vv['sid'];
            $youranswer[] = $vv['answer'];
            $sanswer = M("Testsubject")->where("id=$vv[sid]")->select();
            $result = explode('|||', $sanswer[0]['answer']);
            if ($sanswer[0]['type'] == 2) {
                if ($vv['answer'] == $result) {
                    $theresult[$kk]['status'] = 1;
                }
            } else {
                if ($vv['answer'] == $result[0]) {
                    $theresult[$kk]['status'] = 1;
                } else {
                    $theresult[$kk]['status'] = 0;
                }
            }
            $theresult[$kk]['sid'] = $vv['sid'];
            $theresult[$kk]['question'] = $sanswer[0]['title'];
            $theresult[$kk]['type'] = $sanswer[0]['type'];
            $theresult[$kk]['option'] = $sanswer[0]['option'];
            $theresult[$kk]['yanswer'] = $vv['answer'];
            $theresult[$kk]['manswer'] = $result;
        }
        //保存测试历史记录
        // echo $vv['sid'].'---'.$vv['answer'].'==='.$result[0].'<br>';
        $analysis = M('analysis');
        session_start();
        $analysisdata['uid'] = $_SESSION['user_id'];
        $accountdata = M('member')->where("id=" . $_SESSION['user_id'])->select();
        $analysisdata['member'] = $accountdata[0]['realname'];
        $analysisdata['tid'] = $sId[0]['id'];
        $analysisdata['testbase'] = $sId[0]['title'];
        $analysisdata['options'] = implode(',', $thisoption);
        $analysisdata['answer'] = implode(',', $youranswer);
        $analysisdata['status'] = 1;
        $analysisdata['createat'] = time();
        if (false == $analysis->add($analysisdata)) {
            $this->error('数据库繁忙,请稍后再试！');
        }
        $this->assign('theresult', $theresult);
        $this->display();
    }

    public function mypapers() {
        $this->issignin();
        $module = M('analysis');
        session_start();
        $uid = $_SESSION['user_id'];
        $map['status'] = 1;
        $map['uid'] = $uid;
        $mypapers = $module->where($map)->select();
        $this->assign('mypapers', $mypapers);
        $this->set_seo_meta('过往测试');
        $this->display();
    }

    public function papermore() {
        $this->issignin();
        $module = M("analysis");
        session_start();
        $map['id'] = intval($_GET['id']);
        $map['uid'] = $_SESSION['user_id'];
        $answerdata = $module->where($map)->select();
        $opts = explode(',', $answerdata[0]['options']);
        for ($i = 0; $i < count($opts); $i++) {
            $subjects[] = M("Testsubject")->where('id=' . $opts[$i])->select();
        }
        foreach ($subjects as $kk => $vv) {
            $theanswer[] = $vv[0]['answer'];
            $theresult[$kk]['question'] = $vv[0]['title'];
            $theresult[$kk]['type'] = $vv[0]['type'];
            $theresult[$kk]['answer'] = $vv[0]['answer'];
        }
        $ans = explode(',', $answerdata[0]['answer']);
        for ($i = 0; $i < count($theresult); $i++) {
            if ($ans[$i] == $theresult[$i]['answer']) {
                $theresult[$i]['status'] = 1;
            } else {
                $theresult[$i]['status'] = 0;
            }
        }
        $this->assign('theresult', $theresult);
        $this->display();
    }

    public function paperdel() {
        $this->issignin();
        $id = intval($_GET['id']);
        $module = M('analysis');
        $data['id'] = $id;
        $data['status'] = 0;
        if ($module->save($data)) {
            $this->success('删除成功!');
        } else {
            $this->error('数据库繁忙,请稍后再试!');
        }
    }

    public function userinfo() {
        $this->issignin();
        $module = M("Member");
        session_start();
        $id = $_SESSION['user_id'];
        $userinfo = $module->where('id=' . $id)->find();
        $this->assign('userinfo', $userinfo);
        $this->set_seo_meta('用户信息');
        $this->display();
    }

    public function douserinfo() {
        $this->issignin();
        $module = M('Member');
        $data['id'] = $_POST['id'];
        $data['passwd'] = md5(strtolower($_POST['upass']));
        if ($module->save($data)) {
            $this->success('修改成功!');
        } else {
            $this->error('数据库繁忙,请稍后再试!');
        }
    }

    public function signup() {
        $latest = D('Form')->limit(10)->order('id desc')->select();
        $category = D('Form')->limit(10)->order('id desc')->select();
        $this->assign('latest', $latest);
        $this->assign('category', $category);
        $this->set_seo_meta('用户注册');
        $this->display();
    }

    public function dosignup() {
        $module = D('Member');
        $data = array();
//        $data['email'] = addslashes(trim($_POST['TxtEmail']));
        $data['login_spm'] = addslashes(trim($_POST['spm']));
        $data['login_zsm'] = addslashes(trim($_POST['zsm']));
        $data['realname'] = addslashes(trim($_POST['uname']));
        $data['passwd'] = addslashes(trim($_POST['upass']));
        $data['status'] = 0;
        $data['createat'] = time();
        $act = $module->add($data);
        if ($act) {
            $this->success('用户注册成功,现在你可以使用注册的帐号登录了.');
        } else {
            $this->error('数据库繁忙,请稍后再试!');
        }
    }

    public function signin() {
        $module = M('Form');
        $latest = $module->limit(10)->order('id desc')->select();
        $this->assign('latest', $latest);
        $this->set_seo_meta('用户登录');
        $this->display();
    }

    public function dosignin() {
        $module = M('Member');
        $map['login'] = addslashes(trim($_POST['spm']));
        $map['passwd'] = md5(strtolower(addslashes(trim($_POST['upass']))));
        $map['status'] = 1;
        $account = $module->where($map)->select();
        if (!empty($account)) {
            session_start();
            session_regenerate_id(); //解决session固定会话攻击
            $_SESSION['user_id'] = $account[0]['id'];
            $this->success('登录成功!', '__URL__/papers');
        } else {
            $this->error('用户名或密码错误,返回重新登录!');
        }
    }

    private function issignin() {
        $return = true;
        session_start();
        if (!isset($_SESSION['user_id'])) {
            $this->redirect('/Index/signin');
        }
        return $return;
    }

    public function signout() {
        session_start();
        $module = M('Member');
        $account['lastlogin'] = time();
        $account['id'] = $_SESSION['account_id'];
        $module->save($account);
        if (session_destroy ()) {
            $this->success('已成功退出登录!');
        }
    }

    private function set_seo_meta($title, $keywords) {
        $argstitle = '浙江省温州市第一医院';
        $argskeywords = '继续教育平台,素质测试,学习平台';
        if ($title != '') {
            $argstitle = $title . '_' . $argstitle;
        }
        if ($keywords != '') {
            $keywords = $keywords . '_' . $argskeywords;
        }
        $this->assign('title', $argstitle);
        $this->assign('keywords', $keywords);
    }

}

